package logic

import (
	"context"
	"good_rpc/models"

	"good_rpc/internal/svc"
	"good_rpc/pb/good"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateGoodLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateGoodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateGoodLogic {
	return &CreateGoodLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateGoodLogic) CreateGood(in *good.GoodInfo) (*good.GoodInfo, error) {
	result, err := l.svcCtx.GoodModel.Insert(l.ctx, &models.Good{Name: in.Name, Stock: in.Stock, Price: in.Price})
	if err != nil {
		l.Logger.Errorf("CreateGood insert failed: name=%s, stock=%d, price=%d, error: %v", in.Name, in.Stock, in.Price, err)
		return nil, err
	}
	goodID, err := result.LastInsertId()
	if err != nil {
		l.Logger.Errorf("CreateGood get last insert id failed: name=%s, stock=%d, price=%d, error: %v", in.Name, in.Stock, in.Price, err)
		return nil, err
	}
	return &good.GoodInfo{Id: goodID, Name: in.Name, Stock: in.Stock, Price: in.Price}, nil
}
